package 多线程.Unsafe;
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class UnsafeDemo2 {
    volatile long state = 0;// 变量
    static Unsafe unsafe;// 获取Unsafe的实例
    static long stateOffset;// 记录变量state在类UnSafeDemo类中的偏移值
    static {

        try {
            Field field;
            //使用反射获取Unsafe类的成员交量theUnsafe
            field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);//设置为可存取
            unsafe = (Unsafe) field.get(null);//获取该变量的值
            //获取state在UnSafeDemo中的偏移量
            stateOffset = unsafe.objectFieldOffset(UnsafeDemo2.class.getDeclaredField("state"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        UnsafeDemo2 uDemo = new UnsafeDemo2();
        System.out.println("before CAS:"+uDemo.state);
        Boolean success = unsafe.compareAndSwapInt(uDemo, stateOffset, 0, 1);
        System.out.println(success);
        System.out.println("after CAS:"+uDemo.state);
    }
}
